<template>
  <section class="todoapp">
    <header class="header">
      <h1>todos</h1>
      <input class="new-todo" placeholder="What needs to be done?" autofocus @keyup.enter="addTodoItem">
    </header>
    <!-- This section should be hidden by default and shown when there are todos -->
    <section class="main">
      <input id="toggle-all" class="toggle-all" type="checkbox" @change="toggleAllIsDone">
      <label for="toggle-all">Mark all as complete</label>
      <ul class="todo-list">
        <!-- These are here just to show the structure of the list items -->
        <!-- List items should get the class `editing` when editing and `completed` when marked as completed -->
        <!-- <li :class="[item.isDone?'completed':'',item.id===editId?'editing':'']" v-for="item in filterTodoList" :key="item.id"> -->
        <li :class="{completed:item.isDone,editing:item.id===editId}" v-for="item in filterTodoList" :key="item.id">
          <div class="view">
            <input class="toggle" type="checkbox" v-model="item.isDone">
            <label @dblclick="goEdit(item,$event)">{{ item.text }}</label>
            <button class="destroy" @click="deleteTodoItemById(item.id)"></button>
          </div>
          <input class="edit" v-model="preText" @keyup.enter="doEdit" @blur="resetTodo" @keyup.esc="resetTodo">
        </li>
        <!-- <li>
          <div class="view">
            <input class="toggle" type="checkbox">
            <label>Buy a unicorn</label>
            <button class="destroy"></button>
          </div>
          <input class="edit" value="Rule the web">
        </li> -->
      </ul>
    </section>
    <!-- This footer should be hidden by default and shown when there are todos -->
    <footer class="footer">
      <!-- This should be `0 items left` by default -->
      <span class="todo-count"><strong>{{ leftNum }}</strong> item left</span>
      <!-- Remove this if you don't implement routing -->
      <ul class="filters">
        <li>
          <a class="selected" href="#/" @click.prevent="filterTodoItems('all')">All</a>
        </li>
        <li>
          <a href="#/active" @click.prevent="filterTodoItems('active')">Active</a>
        </li>
        <li>
          <a href="#/completed" @click.prevent="filterTodoItems('completed')">Completed</a>
        </li>
      </ul>
      <!-- Hidden if no completed items are left ↓ -->
      <button class="clear-completed" @click="clearCompleted">Clear completed</button>
    </footer>
  </section>
  <footer class="info">
    <p>Double-click to edit a todo</p>
    <!-- Remove the below line ↓ -->
    <p>Template by <a href="http://sindresorhus.com">Sindre Sorhus</a></p>
    <!-- Change this out with your name and url ↓ -->
    <p>Created by <a href="http://todomvc.com">you</a></p>
    <p>Part of <a href="http://todomvc.com">TodoMVC</a></p>
  </footer>
</template>
<script setup>
import {ref,computed,nextTick,watch,watchEffect,onMounted} from 'vue'
// const todoList = ref([
//   {
//     id:1,
//     text:'敲200行代码',
//     isDone:true
//   },
//   {
//     id:2,
//     text:'跑10公里',
//     isDone:false
//   }
// ])
const todoList = ref(JSON.parse(window.localStorage.getItem('2207todoList') || '[]'))


// 监听 todoList 改变
watch(()=>todoList.value,(newVal)=>{
    console.log("newVal===>",newVal);
    window.localStorage.setItem('2207todoList',JSON.stringify(todoList.value))
  },{
    deep:true
  })

// 添加待办事项
const addTodoItem = (e)=>{
  // console.log("e==>",e.target.value);
  const value = e.target.value
  if(value){
    todoList.value.push({
      id:Date.now(),
      text:value,
      isDone:false
    })
    // 清除输入框内容
    e.target.value = ""
  }else{
    alert("待办事项不能为空！！！")
  } 
}

// 全部完成/非全部完成
const toggleAllIsDone = (e)=>{
  // console.log("e==>",e.target.checked);
  todoList.value.forEach(item=>item.isDone = e.target.checked)
}

// 剩余未完成事项的个数
const leftNum = computed(()=>{
    return todoList.value.filter(item=>!item.isDone).length
})

// 通过 ID 删除选项
const deleteTodoItemById = (id)=>{
  const index = todoList.value.findIndex(item=>item.id === id)
  // 删除
  todoList.value.splice(index,1)
}

// 清除已完成
const clearCompleted = ()=>{
  todoList.value = todoList.value.filter(item=>!item.isDone)
}


// 过滤待办事项 state : all active completed
// const filterTodoItems = (state)=>{
//   if(state === 'active'){
//     todoList.value = todoList.value.filter(item=>!item.isDone)
//   }else if(state === 'completed'){
//     todoList.value = todoList.value.filter(item=>item.isDone)
//   }else{
   
//   }
// }
const state = ref('all') // state : all active completed
const filterTodoItems = (s)=>{
  state.value = s
}
const filterValue = {
  'all':()=>todoList.value,
  'active':()=>todoList.value.filter(item=>!item.isDone),
  'completed':()=>todoList.value.filter(item=>item.isDone)
}
const filterTodoList = computed(()=>{

  // if(state.value === 'active'){
  //   return todoList.value.filter(item=>!item.isDone)
  // }else if(state.value === 'completed'){
  //   return todoList.value.filter(item=>item.isDone)
  // }else{
  //  return todoList.value
  // }
  return filterValue[state.value]()
})

// 双击编辑
const editId = ref('') // 修改 item 的 id
const preText = ref('') // 修改前的内容
const goEdit = (item,e)=>{
  if(item.isDone) {
    return alert('已完成的不能修改')
  }

  editId.value = item.id
  preText.value = item.text
  // 输入框获取焦点
  // console.log("e.target.parentNode==>",e.target.parentNode.nextSibling);
  nextTick(()=>{
    e.target.parentNode.nextSibling.focus()
  })
}

// 
const doEdit = ()=>{
  todoList.value.find(item=>item.id === editId.value).text = preText.value;
  // 清除编辑状态
  editId.value = ""
  preText.value = ""
}
// 市区焦点
const resetTodo = ()=>{
   // 清除编辑状态
   editId.value = ""
   preText.value = ""
}
</script>
<style>
@import './base.css';
@import './index.css';
</style>